package com.esyoga.yoyoga.handler;

import com.esyoga.yoyoga.pojo.*;
import com.esyoga.yoyoga.pojo.DTO.GymAgreementDTO;
import com.esyoga.yoyoga.pojo.DTO.GymOrdersDTO;
import com.esyoga.yoyoga.pojo.DTO.TrainerAgreementDTO;
import com.esyoga.yoyoga.pojo.DTO.TrainerWithStarDTO;
import com.esyoga.yoyoga.service.GymService;
import com.esyoga.yoyoga.util.CutPagesUtil;
import com.esyoga.yoyoga.util.PictureInvertUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/*
学员页面场馆部分
 */
@Data
@Controller
@RequestMapping("/gym")
public class GymHandler {

    @Resource
    private GymService gymService;

    private Map<String, Object> result = new HashMap<>();

    /*分页显示该场馆所有签约教练*/
    @RequestMapping("/findTrainersByGymid")
    @ResponseBody
    public Map<String, Object> findTrainersByGymid(int gid,int page){
        List<TTrainer> tTrainers=gymService.findTrainersByGymid(gid);
        List<TrainerWithStarDTO> trainerWithStarDTOS=new ArrayList<>();
        for (TTrainer t:tTrainers) {
            BigDecimal star=gymService.countStarForTrainer(t.gettId());
            TrainerWithStarDTO trainerWithStarDTO=new TrainerWithStarDTO(star,t);
            trainerWithStarDTOS.add(trainerWithStarDTO);
        }
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,4);
        List<TrainerWithStarDTO> tTrainersList = CutPagesUtil.getPages(trainerWithStarDTOS);
        int totalPage = CutPagesUtil.getTotalPage();

        result.put("rows",tTrainersList);
        result.put("total",totalPage);
        return result;
    }

    /*根据gid查看所有的签约审核*/
    @RequestMapping("/findTrainerAgreementsByGymid")
    @ResponseBody
    public Map<String, Object> findTGymAgreementsByGymid(int gid,int page){
        List<TrainerAgreementDTO> trainerAgreementDTOS=gymService.findTTrainerAgreementsByGymid(gid);
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<TrainerAgreementDTO> tTrainersAgreementList = CutPagesUtil.getPages(trainerAgreementDTOS);
        int totalPage = CutPagesUtil.getTotalPage();
        result.put("rows",tTrainersAgreementList);
        result.put("total",totalPage);
        return result;
    }

    /*教练签约审核*/
    @RequestMapping("/contractAudit")
    @ResponseBody
    public void contractAudit(int taid, int flag){
        gymService.contractAudit(taid, flag);
    }

    /*场馆与教练解约*/
    @RequestMapping("/rescissionWithTrainer")
    @ResponseBody
    public void rescissionWithTrainer(int gid,int tid){
        gymService.rescissionWithTrainer(gid, tid);
    }

    /*订单管理，分页显示该场馆所有订单*/
    @RequestMapping("/findOrdersByGymid")
    @ResponseBody
    public Map<String, Object> findOrdersByGymid(int gid,int page){
        List<GymOrdersDTO> gymOrdersDTOS=gymService.findOrdersByGymid(gid);
        if (gymOrdersDTOS==null){
            return null;
        }
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<GymOrdersDTO> GymOrdersList = CutPagesUtil.getPages(gymOrdersDTOS);
        int totalPage = CutPagesUtil.getTotalPage();
        result.put("rows",GymOrdersList);
        result.put("total",totalPage);
        return result;
    }

    /*查场馆余额*/
    @RequestMapping("/findBalanceByGid")
    @ResponseBody
    public BigDecimal findBalanceByGid(int gid){
        return gymService.findBalanceByGid(gid);
    }

    /*场馆发起与平台签约的请求*/
    @RequestMapping("/applicationForSignature")
    @ResponseBody
    public String applicationForSignature(int gid,double platformratio,BigDecimal joinBanlance){
        return gymService.applicationForSignature(gid, platformratio, joinBanlance);
    }

    /*查询场馆信息*/
    @RequestMapping("/findInformation")
    @ResponseBody
    public TGym findInformation(int gid){
           return gymService.findGymByGid(gid);
    }

    /*根据教练id计算教练星级*/
    @RequestMapping("/countStarByTid")
    @ResponseBody
    public BigDecimal countStarByTid(int tid){
        return gymService.countStarForTrainer(tid);
    }

    /*场馆修改信息*/
    @RequestMapping("/InformationModify")
    @ResponseBody
    public String InformationModify(TGym tGym, @RequestParam MultipartFile[] file, HttpServletRequest request) throws IOException {
        //1.将文件保存到Tomcat服务器本地
        //1.1.获取保存文件的文件夹的路径
        String path =  request.getServletContext().getRealPath("/image");
        File dir = new File(path);
        //获得webapp文件夹的file对象
        File webapp = dir.getParentFile();
        //获取/创建image文件夹
        File image = new File(webapp, "image");
        if (!image.exists()) {
            image.mkdirs();//创建文件夹
        }
        List<String> imgsName=new ArrayList<>();
        for (MultipartFile f:file) {
            System.out.println(f);
            String fileName = f.getOriginalFilename();
            //生成新文件名
            String newName = UUID.randomUUID().toString();
            //得到文件后缀名
            String type = fileName.substring(fileName.lastIndexOf("."));
            //
            newName+=type;
            //拼接新文件的路径
            imgsName.add(newName);
            File uploadFile  = new File(image,newName);
            //1.2.将文件保存到服务器本地
            f.transferTo(uploadFile);
        }
        imgsName.add(tGym.getgImage());
        //2.1.获取文件的路径（相对路径），将所有的注册信息保存到数据库
        tGym.setgImage(PictureInvertUtil.getPathsString(imgsName));
        gymService.InformationModify(tGym);
        return "修改成功";
    }

    //场馆信息展示(分页显示)
    @RequestMapping("/findAllGyms")
    @ResponseBody
    public Map<String,Object> findAllGyms(Integer page, @RequestParam(value ="gName",required = false,defaultValue = "")String gName) {
       //设置查找范围，page：查询的页码，pageSize:显示条数
        //PageHelper.startPage(page, 2);
       // System.out.println(page);

        //设置模糊查询
        gName = "%" + gName + "%";
        //根据场馆的名字进行模糊查询,获得场馆集合
        List<TGym> tGyms=gymService.findAllGyms(gName);
       /* tGyms.forEach(e-> System.out.println(e));*/
        //封装列表信息
        //PageInfo<TGym> pageInfo=new PageInfo<>(tGyms);
        //获取查出的总记录数
        //long total=pageInfo.getTotal();
        //获取当前页数据
        //List<TGym> tGymList=pageInfo.getList().subList((page-1)*2,page*2);
        /*System.out.println("=================================");*/
        /*tGymList.forEach(e-> System.out.println(e));*/
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,2);
        List<TGym> tGymList = CutPagesUtil.getPages(tGyms);
        int total = CutPagesUtil.getTotalPage();
        Map<String,Object> result=new HashMap<String,Object>();
        result.put("total",total);
        result.put("currentMessage",tGymList);
        return result;
    }
    //场馆私教，全部显示以及详细介绍，根据所在场馆id查询合约表的私教id集合，再去私教表查询对应信息
    @RequestMapping("/findAllTrainersByGymId")
    @ResponseBody
    public List<TTrainer> findAllTrainersByGymId(Integer gId){

        List<TTrainer> tTrainers= gymService.findAllTrainersByGymId(gId);
        return tTrainers;
    }



    /**
     *
     * @param page 当前页码
     * @return
     */
    @GetMapping("/selectGyms")
    @ResponseBody
    public Map<String, Object> selectGyms(Integer page){
        //设置查找的范围，pageSize:服务写死
        PageHelper.startPage(page, 20);
        //查找所有场馆信息
        List<TGym> gyms = gymService.selectTGyms();
        //封装列表信息
        PageInfo<TGym> pageInfo = new PageInfo<>(gyms);
        //获取总记录数
        long total = pageInfo.getTotal();
        //获取当前页数据列表
        List<TGym> gymsList = pageInfo.getList();
        //存储数据对象
        result.put("rows",gymsList);
        result.put("total",total);
        return result;
    }



}
